﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Configuration;

namespace myCollection
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Shown(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.db == "")
            {
                MessageBox.Show("Please select place to new database.", "New DB...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    newDBFile(saveFileDialog1.FileName);
                }
                else
                {
                    System.Environment.Exit(0);
                }
            }
            else
            {
                if (File.Exists(Properties.Settings.Default.db) == false)
                {
                    if (MessageBox.Show("File: " + Properties.Settings.Default.db + " not found!\nOpen file from diffrent location?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.Yes)
                    {
                        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            loadDBFile(openFileDialog1.FileName);
                        }
                        else
                        {
                            System.Environment.Exit(0);
                        }
                    }
                    else
                    {
                        if (MessageBox.Show("Create new database file?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {
                            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                newDBFile(saveFileDialog1.FileName);
                            }
                            else
                            {
                                System.Environment.Exit(0);
                            }
                        }
                        else
                        {
                            System.Environment.Exit(0);
                        }
                    }
                }
                else
                {
                    this.refreshDGV();
                }
            }
        }

        private void saveSettings(string filedb)
        {
            Properties.Settings.Default.db = filedb;
            Properties.Settings.Default.dirfiles = Path.GetDirectoryName(filedb) + "\\mycfiles";
            Properties.Settings.Default.Save();
            if (Directory.Exists(Properties.Settings.Default.dirfiles) == false)
            {
                Directory.CreateDirectory(Properties.Settings.Default.dirfiles);
            }
            MessageBox.Show("Database is ready!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void newDBFile(string filedb)
        {
            SQLite sqlite0 = new SQLite();
            try
            {
                sqlite0 = new SQLite();
                sqlite0.Connect(filedb);
                sqlite0.InitDB();
                sqlite0.Disconnect();
                this.saveSettings(filedb);
                this.refreshDGV();
            }
            catch (System.Security.SecurityException ex0)
            {
                MessageBox.Show("No access to file: " + filedb + "\n" + ex0, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(5);
            }
            catch (System.UnauthorizedAccessException ex1)
            {
                MessageBox.Show("No access to file: " + filedb + "\n" + ex1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(5);
            }
            catch (System.IO.IOException ex2)
            {
                MessageBox.Show("No access to file: " + filedb + "\n" + ex2, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(5);
            }
        }

        private void loadDBFile(string filedb)
        {
            if (File.Exists(filedb))
            {
                try
                {
                    FileStream fileStream = new FileStream(filedb, FileMode.Open, FileAccess.Write);
                    this.saveSettings(filedb);
                    this.refreshDGV();
                }
                catch (System.Security.SecurityException ex0)
                {
                    MessageBox.Show("No access to file: " + filedb + "\n" + ex0, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(5);
                }
                catch (System.UnauthorizedAccessException ex1)
                {
                    MessageBox.Show("No access to file: " + filedb + "\n" + ex1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(5);
                }
                catch (System.IO.IOException ex2)
                {
                    MessageBox.Show("No access to file: " + filedb + "\n" + ex2, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(5);
                }
            }
        }

        private void cbSearchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbSearchType.Text != "" && cbSearchType.Text != "Info")
            {
                cbSearchDictionary.Enabled = true;
                SQLite sqlite0 = new SQLite();
                sqlite0.Connect();
                DataTable dt = new DataTable();
                switch (cbSearchType.SelectedIndex)
                {
                    case 1:
                        dt = sqlite0.GetDictionary(Dictionary.TypeD.MediaType, "");
                        break;
                    case 2:
                        dt = sqlite0.GetDictionary(Dictionary.TypeD.DataType, "");
                        break;
                    case 3:
                        dt = sqlite0.GetDictionary(Dictionary.TypeD.Category, "");
                        break;
                    case 4:
                        dt = sqlite0.GetDictionary(Dictionary.TypeD.Place, "");
                        break;
                }
                cbSearchDictionary.DataSource = dt;
                sqlite0.Disconnect();
            }
            else
            {
                cbSearchDictionary.Enabled = false;
            }
        }

        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Info().ShowDialog();
        }

        private void dictionaryMediaTypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Dictionary(Dictionary.TypeD.MediaType).ShowDialog();
        }

        private void dictionaryDataTypeStripMenuItem_Click(object sender, EventArgs e)
        {
            new Dictionary(Dictionary.TypeD.DataType).ShowDialog();
        }

        private void dictionaryCategoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Dictionary(Dictionary.TypeD.Category).ShowDialog();
        }

        private void dictionaryPlacesStripMenuItem1_Click(object sender, EventArgs e)
        {
            new Dictionary(Dictionary.TypeD.Place).ShowDialog();
        }

        private void btAddRecord_Click(object sender, EventArgs e)
        {
            new Record().ShowDialog();
            this.refreshDGV(((dgvRecords.Rows.Count > 0) ? dgvRecords.CurrentCell.RowIndex : 0));
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void newDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newDBFile(saveFileDialog1.FileName);
            }
        }

        private void openDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                loadDBFile(openFileDialog1.FileName);
            }
        }

        private void refreshDGV(int rowIndex = 0)
        {
            this.Text = "My Collection " + Properties.Settings.Default.db;
            dgvRecords.Rows.Clear();
            SQLite sqlite = new SQLite();
            sqlite.Connect();
            DataTable dt = new DataTable();
            if (cbSearchDictionary.Enabled)
            {
                Dictionary.TypeD type0 = Dictionary.TypeD.MediaType;;
                switch (cbSearchType.SelectedIndex)
                {
                    case 1: type0 = Dictionary.TypeD.MediaType;
                        break;
                    case 2: type0 = Dictionary.TypeD.DataType;
                        break;
                    case 3: type0 = Dictionary.TypeD.Category;
                        break;
                    case 4: type0 = Dictionary.TypeD.Place;
                        break;
                }
                dt = sqlite.GetRecords(tbSearchByName.Text, type0, int.Parse(cbSearchDictionary.SelectedValue.ToString()));
            }
            else
            {
                if (cbSearchType.Text == "")
                {
                    dt = sqlite.GetRecords(tbSearchByName.Text);
                }
                else
                {
                    dt = sqlite.GetRecordsInfo(tbSearchByName.Text);
                }
            }
            sqlite.Disconnect();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dgvRecords.Rows.Add(dt.Rows[i]["id"].ToString(), (i + 1).ToString(), dt.Rows[i]["name"].ToString(), dt.Rows[i]["mediatype"].ToString(), dt.Rows[i]["datatype"].ToString(), dt.Rows[i]["category"].ToString(), dt.Rows[i]["place"].ToString());
            }
            if (rowIndex > 0 && dgvRecords.Rows.Count > 0 && rowIndex < dgvRecords.Rows.Count)
            {
                dgvRecords.Rows[rowIndex].Cells[1].Selected = true;
            }
        }

        private void btDelRecord_Click(object sender, EventArgs e)
        {
            if (dgvRecords.CurrentCell.RowIndex > -1)
            {
                if (MessageBox.Show("Delete: " + dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["name"].Value.ToString() + " ?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    SQLite sqlite = new SQLite();
                    sqlite.Connect();
                    DataTable dt = new DataTable();
                    dt = sqlite.GetRecordFiles(int.Parse(dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["id"].Value.ToString()));
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        File.Delete(Properties.Settings.Default.dirfiles + "\\" + dt.Rows[i]["file"].ToString());
                    }
                    sqlite.DeleteRecord(int.Parse(dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["id"].Value.ToString()));
                    sqlite.DeleteRecordFiles(int.Parse(dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["id"].Value.ToString()));
                    sqlite.Disconnect();
                    this.refreshDGV(((dgvRecords.Rows.Count > 0) ? dgvRecords.CurrentCell.RowIndex : 0));
                }
            }
        }

        private void btEditRecord_Click(object sender, EventArgs e)
        {
            new Record(int.Parse(dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["id"].Value.ToString())).ShowDialog();
            this.refreshDGV(((dgvRecords.Rows.Count > 0) ? dgvRecords.CurrentCell.RowIndex : 0));
        }

        private void btExport_Click(object sender, EventArgs e)
        {
            if (exportFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string row = "", row0 = "";
                if (Path.GetExtension(exportFileDialog.FileName) == ".txt")
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportFileDialog.FileName))
                    {
                        int[] cellSize = new int[dgvRecords.Columns.Count];
                        for (int x = 0; x < dgvRecords.Columns.Count; x++)
                        {
                            cellSize[x] = dgvRecords.Columns[x].HeaderText.Length;
                        }
                        for (int y = 0; y < dgvRecords.Rows.Count; y++)
                        {
                            for (int x = 0; x < dgvRecords.Columns.Count; x++)
                            {
                                if (cellSize[x] < dgvRecords.Rows[y].Cells[x].Value.ToString().Length)
                                {
                                    cellSize[x] = dgvRecords.Rows[y].Cells[x].Value.ToString().Length;
                                }
                            }
                        }
                        for (int x = 0; x < dgvRecords.ColumnCount; x++)
                        {
                            if (dgvRecords.Columns[x].Visible)
                            {
                                row0 += "+-";
                                for (int i = 0; i < (cellSize[x] + 1); i++)
                                {
                                    row0 += "-";
                                }
                                row += "| ";
                                row += dgvRecords.Columns[x].HeaderText;
                                if (cellSize[x] > dgvRecords.Columns[x].HeaderText.Length)
                                {
                                    for (int i = 0; i < (cellSize[x] - dgvRecords.Columns[x].HeaderText.Length); i++)
                                    {
                                        row += " ";
                                    }
                                }
                                row += " ";
                                if (x == dgvRecords.ColumnCount - 1)
                                {
                                    row += " |";
                                    row0 += "-+";
                                }
                            }
                        }
                        file.WriteLine(row0);
                        file.WriteLine(row);
                        file.WriteLine(row0);
                        for (int y = 0; y < dgvRecords.Rows.Count; y++)
                        {
                            row = "";
                            for (int x = 0; x < dgvRecords.ColumnCount; x++)
                            {
                                if (dgvRecords.Columns[x].Visible)
                                {
                                    row += "| ";
                                    row += dgvRecords.Rows[y].Cells[x].Value.ToString();
                                    if (cellSize[x] > dgvRecords.Rows[y].Cells[x].Value.ToString().Length)
                                    {
                                        for (int i = 0; i < (cellSize[x] - dgvRecords.Rows[y].Cells[x].Value.ToString().Length); i++)
                                        {
                                            row += " ";
                                        }
                                    }
                                    row += " ";
                                    if (x == dgvRecords.ColumnCount - 1)
                                    {
                                        row += " |";
                                    }
                                }
                            }
                            file.WriteLine(row);
                        }
                        file.WriteLine(row0);
                        MessageBox.Show("Export done!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else if (Path.GetExtension(exportFileDialog.FileName) == ".csv")
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportFileDialog.FileName))
                    {
                        for (int x = 0; x < dgvRecords.ColumnCount; x++)
                        {
                            if (dgvRecords.Columns[x].Visible)
                            {
                                row += dgvRecords.Columns[x].HeaderText;
                                if (x != dgvRecords.ColumnCount - 1)
                                {
                                    row += ";";
                                }
                            }
                        }
                        file.WriteLine(row);
                        for (int y = 0; y < dgvRecords.Rows.Count; y++)
                        {
                            row = "";
                            for (int x = 0; x < dgvRecords.ColumnCount; x++)
                            {
                                if (dgvRecords.Columns[x].Visible)
                                {
                                    row += dgvRecords.Rows[y].Cells[x].Value.ToString();
                                    if (x != dgvRecords.ColumnCount - 1)
                                    {
                                        row += ";";
                                    }
                                }
                            }
                            file.WriteLine(row);
                        }
                        MessageBox.Show("Export done!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            this.refreshDGV();
        }

        private void tbSearchByName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.refreshDGV();
            }
        }

        private void dgvRecords_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            new Record(int.Parse(dgvRecords.Rows[dgvRecords.CurrentCell.RowIndex].Cells["id"].Value.ToString())).ShowDialog();
            this.refreshDGV(((dgvRecords.Rows.Count > 0) ? dgvRecords.CurrentCell.RowIndex : 0));
        }

        private void indexFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new IndexFiles().ShowDialog();
        }
       
    }
}
